<template>
  <div style="height:100%">
    <div class="title">聊天室</div>

    <div style="height:2%">
      <span style="float: left" class="onlineCount">
        当前在线人数：
        <font color="green">{{ count }}</font>
      </span>
    </div>

    <div class="contentCls">
      <el-scrollbar ref="myScrollbar" style="height:100%">
        <el-row v-for="(item, index) in msgRecord" :key="index">
          <el-col :span="24">
            <span>
              <span class="itime">
                {{
                  item.itime === "" ? formDate(date) : formDate(item.itime)
                }}
              </span>
              <br>
              {{ item.sender }} :
              <el-tag type="success" size="small">{{ item.content }}</el-tag>
            </span>
            <br>
            <br>
          </el-col>
        </el-row>
      </el-scrollbar>
    </div>

    <div class="mtop" style="height:5%">
      <el-row :span="24">
        <el-col>
          <el-input v-model="content" placeholder="请输入内容" @keyup.enter.native="sendMsg" />
        </el-col>
      </el-row>
    </div>

    <div class="mtop" style="height:5%">
      <el-row :span="24">
        <el-col>
          <el-button class="btn" type="primary" @click="sendMsg">发 送</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import chat from '../../api/chat'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      date: new Date(),
      admin: '',
      count: 0,
      content: '',
      msgRecord: [],
      toUserId: '',
      msg: {
        content: '',
        id: 0,
        ip: '',
        itime: '',
        sender: '系统通知',
        toUserId: ''
      }
    }
  },
  mounted() {
    this.initWebSocket()
    this.getMsg()
  },
  // 当关闭页面时关闭链接（自动下线）
  destroyed() {
    this.wsClose()
  },
  methods: {
    // 初始化服务器建立连接
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      // var cip = returnCitySN["cip"];
      // var cname = returnCitySN["cname"];
      // this.websock = new WebSocket("ws://localhost:9999/imserver/Ip:" + cip + ",姓名:"+ cname);
      this.websock = new WebSocket(
        'ws://120.26.130.99:9999/imserver/admin' +
          Math.floor(Math.random() * 100)
      )
      this.websock.onopen = this.wsOpen
      this.websock.onerror = this.wsError
      this.websock.onmessage = this.wsMessage
      this.websock.onclose = this.wsClose
    },
    wsOpen(e) {},
    wsMessage(e) {
      console.log('收到消息：' + e.data)
      const msg = JSON.parse(e.data)
      // 0:实时更新在线人数
      if (msg.signal === '0') {
        this.count = msg.value
        this.msg.content = msg.desc
        this.msgRecord = this.msgRecord.concat(this.msg)
      }
      // 1:实时更新最新消息
      else if (msg.signal === '1') {
        this.getMsg()
      }
    },
    wsClose(e) {
      console.log('connection closed')
    },
    wsError(e) {
      console.log('WebSocket连接发生错误')
    },

    async getMsg() {
      this.msgRecord = await chat.getMsg()
      console.info(this.msgRecord)
      this.$nextTick(function() {
        this.scrollDown()
      })
    },
    async sendMsg() {
      if (this.content !== '') {
        const params = {
          toUserId: this.toUserId,
          content: this.content
        }
        this.websock.send(JSON.stringify(params))
        this.content = ''
      } else {
        console.info('发送消息不能为空')
      }
    },
    formDate(itime) {
      return dayjs(itime).format('YYYY-MM-DD HH:mm:ss')
    },
    scrollDown() {
      this.$refs['myScrollbar'].wrap.scrollTop = this.$refs[
        'myScrollbar'
      ].wrap.scrollHeight
    }
  }
}
</script>

<style scoped>
.title {
  display: flex;
  align-items: center; /*定义body的元素垂直居中*/
  justify-content: center; /*定义body的里的元素水平居中*/
  height: 10%;
  font-size: 22px;
  font-weight: bold;
}
.contentCls {
  width: 100%;
  height: 70%;
  border: rgb(218, 215, 215) 1px solid;
  border-radius: 5px;
  font-size: 12px;
  color: rgb(135, 160, 172);
  margin-top: 10px;
}
.mtop {
  margin-top: 2%;
}
.btn {
  width: 100%;
}
.onlineCount {
  font-size: 12px;
}
.itime {
  color: rgb(185, 182, 182);
}
</style>
